#  Copyright 2011 Nokia Siemens Networks Oyj
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

import os
import glob


class TemplateCompiler(object):

    def __init__(self, output_folder):
        self._output = output_folder
        self._templates = []

    def _get_changed(self, template_folder, output_folder):
        return [template for template in self._get_templates(template_folder)
                if not self._up_to_date(template, output_folder)]

    def _get_templates(self, template_folder):
        return glob.glob(os.path.join(template_folder, "*.erl"))

    def _up_to_date(self, template, output_folder):
        temp_modified = os.path.getmtime(template)
        compiled = self._get_compile_time(template, output_folder)
        return temp_modified <=compiled

    def _get_compile_time(self, template, output_folder):
        name = os.path.split(template)[-1]
        base = os.path.splitext(name)[-2]
        compiled = os.path.join(output_folder, '%s.beam' % base)
        if not os.path.exists(compiled):
            return 0
        return os.path.getmtime(compiled)

    def add_templates(self, folder):
        if folder not in self._templates:
            self._templates.append(folder)

    def compile(self):
        for folder in self._templates:
            if os.path.exists(folder):
                self._compile_folder(folder)

    def _compile_folder(self, folder):
        changed = self._get_changed(folder, self._output)
        if not changed:
            print '*DEBUG* no changed templates in folder %s' % folder
            return
        print '*DEBUG* compiling templates in folder %s' % folder
        self._execute_compiler(changed, self._output)

    def _execute_compiler(self, templates, output):
        cmd = 'erlc -o "%s" %s' % (output, ' '.join(templates))
        print '*DEBUG* executing compile command %s' % cmd
        rc = os.system(cmd)
        if rc != 0:
            raise Exception('Compilation failed with rc %d' % rc)